/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bifang.gwt.server;

import han.bifang.common.exception.BifangException;
import han.bifang.gwt.client.common.RequestObject;
import han.bifang.gwt.client.common.ResponseObject;
import han.bifang.gwt.client.communicate.BifangGWTService;
import han.bifang.gwt.server.action.BifangGWTAction;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class BifangGWTServlet extends RemoteServiceServlet implements
		BifangGWTService {
	private static Log logger = LogFactory.getLog(BifangGWTServlet.class);

	public BifangGWTServlet() {
		super();

	}

	@Override
	public ResponseObject call(RequestObject req) {
		try {

			BifangGWTAction action = (BifangGWTAction) Class.forName(
					req.getAction()).newInstance();
			System.out.println(req.getAction() + " is called");
			return action.execute(req, this.getThreadLocalRequest(), this
					.getThreadLocalResponse());
		} catch (Throwable e) {
			ResponseObject res = new ResponseObject();
			if (e instanceof BifangException) {
				BifangException be = (BifangException) e;
				logger.error("----error detail----");
				logger.error("error code : " + be.getCode());
				logger.error("error msg : " + be.getMsg());
				if (be.getError() != null) {
					logger.error("error trace : ", be.getError());
				}else{
					logger.error("error trace : ",e);
				}
				res.setCode(be.getCode());
				res.setMsg(be.getMsg());

			} else {
				logger.error("----error detail----");
				logger.error("error code : -9999" );
				logger.error("error msg : " + e.getMessage());
				logger.error("error trace : ",e);
				
				res.setCode("-9999");
				res.setMsg("UNKNOWN ERROR : " + e.getMessage());
			}
			return res;
		}

	}

}
